package com.ruoyi.system.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IProgressTemplateService;
import com.ruoyi.system.service.ISalesOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Service
public class SalesOrderServiceImpl implements ISalesOrderService
{
    @Autowired
    private SalesOrderMapper salesOrderMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private SalesFlowMapper salesFlowMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private QuotationMapper quotationMapper;

    @Autowired
    private IProgressTemplateService progressTemplateService;
    /**
     * 查询销售单列表
     */
    @Override
    public List<SalesOrder> selectSalesOrderList(SalesOrder salesOrder)
    {
        return salesOrderMapper.selectSalesOrderList(salesOrder);
    }

    /**
     * 查询销售单详细明细信息
     */
    @Override
    public Map<String, Object> selectSalesOrderById(Long salesOrderId)
    {
        Map<String, Object> result = new HashMap<>();
        // 获取销售单基本信息
        SalesOrder salesOrder = salesOrderMapper.selectSalesOrderById(salesOrderId);
        // 获取销售单明细
        List<SalesOrderItems> items = salesOrderMapper.selectSalesOrderItemsByOrderId(salesOrderId);

        result.put("salesOrder", salesOrder);
        result.put("items", items);

        return result;
    }

    /**
     * 新增销售单
     */
    @Override
    @Transactional
    public int insertSalesOrder(SalesOrder salesOrder)
    {
        // 1. 设置基础信息
        salesOrder.setOrderDate(new Date());
        salesOrder.setNumber(generateSalesOrderNumber());

        // 2. 获取并设置客户信息
        Customer customer = customerMapper.selectCustomerById(salesOrder.getCustomerId());
        if (customer != null) {
            salesOrder.setCustomerName(customer.getCustomerName());
            salesOrder.setContactPerson(customer.getContactPerson());
            salesOrder.setPhone(customer.getPhone());
        }

        // 3. 设置初始状态为待审批
        salesOrder.setStatus("待审批");

        // 4. 新增销售单
        int rows = salesOrderMapper.insertSalesOrder(salesOrder);

        // 5. 如果有模板ID，创建进度节点
        if (salesOrder.getTemplateId() != null) {
            progressTemplateService.createProgressFromTemplate(salesOrder.getTemplateId(), 
                salesOrder.getSalesOrderId(), salesOrder.getNumber());
        }

        return rows;
    }

    /**
     * 生成销售单编号
     * 生成规则: XS + 年月日 + 4位流水号
     */
    private String generateSalesOrderNumber() {
        // 获取当前日期
        String date = DateUtils.dateTimeNow("yyyyMMdd");
        // 查询当天最大编号
        String prefix = "XS" + date;
        String maxNumber = salesOrderMapper.getMaxNumberByPrefix(prefix);

        int sequence = 1;
        if (maxNumber != null) {
            // 获取当前序列号并加1
            sequence = Integer.parseInt(maxNumber.substring(10)) + 1;
        }

        // 格式化4位流水号
        return prefix + String.format("%04d", sequence);
    }

    /**
     * 修改销售单
     */
    @Override
    @Transactional
    public int updateSalesOrder(SalesOrder salesOrder)
    {
        // 获取原销售单信息
        SalesOrder oldOrder = salesOrderMapper.selectSalesOrderById(salesOrder.getSalesOrderId());

        int rows = salesOrderMapper.updateSalesOrder(salesOrder);

        // 如果状态变更为"已出库",则执行出库操作
        if (rows > 0 && "已出库".equals(salesOrder.getStatus())
            && !salesOrder.getStatus().equals(oldOrder.getStatus())) {
            handleDelivery(salesOrder);
        }

        return rows;
    }

    /**
     * 处理销售单出库
     * 该方法改为private,只允许在状态变更时内部调用
     */
    private void handleDelivery(SalesOrder salesOrder) {
        // 1. 减少库存
        List<SalesOrderItems> items = salesOrderMapper.selectSalesOrderItemsByOrderId(salesOrder.getSalesOrderId());
        for (SalesOrderItems item : items) {
            productMapper.updateStock(item.getProductId(), -item.getQuantity());
        }

        // 2. 生成销售流水
        SalesFlow salesFlow = new SalesFlow();
        salesFlow.setSalesOrderId(salesOrder.getSalesOrderId());
        salesFlow.setCustomerId(salesOrder.getCustomerId());
        salesFlow.setOrderDate(salesOrder.getOrderDate());
        salesFlow.setTotalAmount(salesOrder.getTotalAmount());
        salesFlowMapper.insertSalesFlow(salesFlow);

        // 3. 更新客户统计数据
        Customer customer = new Customer();
        customer.setCustomerId(salesOrder.getCustomerId());
        customer.setDeliveredOrderCount(1); // 增加已发货订单数
        customerMapper.updateCustomer(customer);
    }

    /**
     * 删除销售单
     */
    @Override
    @Transactional
    public int deleteSalesOrderById(Long salesOrderId)
    {
        // 删除明细
        salesOrderMapper.deleteSalesOrderItemsByOrderId(salesOrderId);
        // 删除主表
        return salesOrderMapper.deleteSalesOrderById(salesOrderId);
    }

    /**
     * 批量删除销售单
     */
    @Override
    @Transactional
    public int deleteSalesOrderByIds(Long[] salesOrderIds)
    {
        for (Long salesOrderId : salesOrderIds)
        {
            // 删除明细
            salesOrderMapper.deleteSalesOrderItemsByOrderId(salesOrderId);
        }
        // 删除主表
        return salesOrderMapper.deleteSalesOrderByIds(salesOrderIds);
    }

    /**
     * 从报价单创建销售单
     */
    @Override
    @Transactional
    public int createFromQuotation(Long quotationId)
    {
        // 1. 获取报价单信息
        Quotation quotation = quotationMapper.getQuotationById(quotationId);
        if (quotation == null) {
            throw new ServiceException("报价单不存在");
        }

        // 2. 获取客户信息
        Customer customer = customerMapper.selectCustomerById(quotation.getCustomerId());
        if (customer == null) {
            throw new ServiceException("客户信息不存在");
        }

        List<QuotationItems> quotationItems = quotationMapper.getQuotationItemsByQuotationId(quotationId);

        // 3. 创建销售单
        SalesOrder salesOrder = new SalesOrder();
        salesOrder.setCustomerId(quotation.getCustomerId());
        // 设置客户相关信息
        salesOrder.setCustomerName(customer.getCustomerName());
        salesOrder.setContactPerson(customer.getContactPerson());
        salesOrder.setPhone(customer.getPhone());
        salesOrder.setAddress(quotation.getAddress());

        salesOrder.setOrderDate(new Date());
        salesOrder.setDeliveryDate(quotation.getQuotationDate());
        salesOrder.setProductAmount(quotation.getProductAmount());
        salesOrder.setTotalAmount(quotation.getTotalAmount());
        salesOrder.setNotes(quotation.getNotes());
        salesOrder.setCreatedBy(quotation.getCreatedBy());

        // 4. 设置进度模板和初始节点(使用与报价单相同的模板)
        salesOrder.setTemplateId(quotation.getTemplateId());
        salesOrder.setNodeId(salesOrderMapper.getPendingApprovalNodeId(quotation.getTemplateId()));
        salesOrder.setStatus("待审核");

        // 5. 生成销售单编号
        salesOrder.setNumber(generateSalesOrderNumber());

        // 6. 新增销售单
        int rows = salesOrderMapper.insertSalesOrder(salesOrder);
        if (rows > 0) {
            // 7. 复制报价单明细到销售单明细
            for (QuotationItems quotationItem : quotationItems) {
                SalesOrderItems orderItem = new SalesOrderItems();
                orderItem.setSalesOrderId(salesOrder.getSalesOrderId());
                orderItem.setProductId(quotationItem.getProductId());
                orderItem.setProductName(quotationItem.getProductName());
                orderItem.setQuantity(quotationItem.getQuantity());
                orderItem.setUnitPrice(quotationItem.getUnitPrice());
                orderItem.setTotalPrice(quotationItem.getTotalPrice());
                salesOrderMapper.insertSalesOrderItems(orderItem);
            }
        }

        return rows;
    }


    /**
     * 新增销售单明细
     */
    @Override
    public int insertSalesOrderItems(SalesOrderItems item)
    {
        Product product = productMapper.selectProductById(item.getProductId());
        if (product != null)
        {
            item.setProductName(product.getProductName());
        }
        return salesOrderMapper.insertSalesOrderItems(item);
    }

    /**
     * 批量新增销售单明细
     */
    @Override
    public int batchInsertSalesOrderItems(List<SalesOrderItems> items)
    {
        for (SalesOrderItems item : items)
        {
            Product product = productMapper.selectProductById(item.getProductId());
            if (product != null)
            {
                item.setProductName(product.getProductName());
            }
        }
        return salesOrderMapper.batchInsertSalesOrderItems(items);
    }
}
